import {Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, ValidationErrors, Validators} from '@angular/forms';
import {UserInfoModel} from '../../../../models/user-info.model';
import {RoleService} from '../../../../service/role.service';
import {UserService} from '../../../../service/user.service';
import {Consts} from '../../../../config/consts';
import {Observable, Observer} from 'rxjs';
import {ApiUrl} from '../../../../config/api-url';
import {BaseService} from '../../../../shared/service/base.service';
import {NzFormatEmitEvent, NzTreeComponent, NzTreeNodeOptions} from 'ng-zorro-antd/tree';

@Component({
  selector: 'app-staff-edit',
  templateUrl: './staff-edit.component.html',
  styleUrls: ['./staff-edit.component.less']
})
export class StaffEditComponent implements OnInit {

  @Input()
  isEditVisible: boolean = false;
  @Output()
  emit: EventEmitter<any> = new EventEmitter();
  isOkLoading = false;
  formModel: FormGroup;
  userInfo: UserInfoModel = new UserInfoModel();
  roleList;
  status: any = 1;
  title: any = '添加员工';
  id: number = 0;

  keyList: any;

  constructor(private fb: FormBuilder,
              private roleService: RoleService,
              private userService: UserService,
              private baseService: BaseService) {

    this.userInfo = JSON.parse(sessionStorage.getItem(Consts.USER_INFO));
  }

  ngOnInit() {
    this.buildForm();
    this.getUserRoleInfo();
    this.findAgency();
  }

  load(data) {
    this.defaultCheckedKeys = [];
    if (data == null) {
      if (this.roleList != null) {
        this.formModel.get('roleId').setValue(this.roleList[0].id);
      }
      this.defaultCheckedKeys.push(1);
      this.id = 0;
      this.title = '添加员工';
      this.formModel.get('username').setValidators([Validators.required]);
      this.formModel.get('password').setValidators([Validators.required]);
      this.formModel.get('confirm').setValidators([this.confirmValidator]);
    } else {
      if (data.agencyIdList != null && data.agencyIdList.length > 0) {
        this.defaultCheckedKeys = data.agencyIdList;
      }
      this.id = data.id;
      this.title = '修改员工';
      this.formModel.reset(data);
      this.formModel.get('username').clearValidators();
      this.formModel.get('username').markAsPristine();
      this.formModel.get('username').updateValueAndValidity();
      this.formModel.get('password').clearValidators();
      this.formModel.get('password').markAsPristine();
      this.formModel.get('password').updateValueAndValidity();
      this.formModel.get('confirm').clearValidators();
      this.formModel.get('confirm').markAsPristine();
      this.formModel.get('confirm').updateValueAndValidity();
    }
    this.defaultCheckedKeys = [...this.defaultCheckedKeys];
  }

  getUserRoleInfo() {
    this.roleService.findUserRoleInfo(res => {
      this.roleList = res.data.roleList;
      if (this.roleList != null) {
        this.formModel.get('roleId').setValue(this.roleList[0].id);
      }
    });
  }

  buildForm() {
    this.formModel = this.fb.group({
      id: [0],
      username: [null, [Validators.required], [this.userNameValidator]],
      password: [null, [Validators.required]],
      confirm: [null, [this.confirmValidator]],
      name: [null],
      birthday: [null],
      roleId: [null],
      mobile: [null],
      sex: [null],
      agencyIdList: [null],
    });
  }

  handleOk() {
    this.isOkLoading = true;
    if (!this.baseService.zorro.validateFormValidate(this.formModel)) {
      this.isOkLoading = false;
      return;
    }
    if (this.formModel.controls.roleId.value == null) {
      this.userService.layer.messageError('请分配角色权限!');
      this.isOkLoading = false;
      return;
    }
    if (!this.isOkLoading) {
      return;
    }
    this.keyList = [];
    let checkedNodeList = this.nzTreeComponent.getCheckedNodeList();
    this.getKey(checkedNodeList);
    this.formModel.get('agencyIdList').setValue(this.keyList);
    if (this.id > 0) {
      this.updateUser(this.formModel.value);
    } else {
      this.addUser(this.formModel.value);
    }
  }

  getKey(data) {
    if (data.length > 0) {
      data.forEach(d => {
        this.keyList.push(d.key);
        this.getKey(d.children);
      });
    }
  }

  updateUser(user) {
    this.userService.update(user, res => {
      if (res.isSuccess) {
        this.userService.layer.messageSuccess('修改成功');
      } else {
        this.userService.layer.messageError('修改失败！' + res.msg);
      }
      this.formModel.reset();
      this.isOkLoading = false;
      this.isEditVisible = false;
      let body = {'cancel': false, 'isEditVisible': this.isEditVisible};
      setTimeout(() => {
        this.emit.emit(body);
      }, 500);
    });
  }

  addUser(user) {
    this.userService.addUserAndAddRole(user, res => {
      if (res.status == 0) {
        this.userService.layer.notificationSuccess('添加用户成功！');
        this.status = res.status;
        this.handleCancel();
      } else {
        this.userService.layer.notificationError('添加用户失败');
      }
      this.isOkLoading = false;
      this.isEditVisible = false;
      let body = {'cancel': false, 'isEditVisible': this.isEditVisible};
      this.formModel.reset({});
      setTimeout(() => {
        this.emit.emit(body);
      }, 500);
    });
  }

  validateConfirmPassword(): void {
    setTimeout(() => this.formModel.controls.confirm.updateValueAndValidity());
  }

//验证密码一至性
  confirmValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return {error: true, required: true};
    } else if (control.value !== this.formModel.controls.password.value) {
      return {confirm: true, error: true};
    }
    return {};
  };

  userNameValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      let reg = /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
      let valid = reg.test(control.value);
      if (!valid) {
        observer.next({correct: true, error: true});
        observer.complete();
      } else {
        this.userService.promise((resolve) => {
          let url = ApiUrl.UserUrl + '/checkUserName?username=' + control.value;
          this.userService.get(url).subscribe(data => {
            resolve(data);
          });
        }).then((res: any) => {
          if (res.status == 0 || this.id > 0) {
            observer.next(null);
          } else {
            observer.next({error: true, duplicated: true});
          }
          observer.complete();
        });
      }
    });


  handleCancel() {
    this.formModel.reset({});
    this.baseService.zorro.clearFormError(this.formModel);
    this.isEditVisible = false;
    let body = {'cancel': true, 'isEditVisible': this.isEditVisible};
    this.isOkLoading = false;
    this.emit.emit(body);
  }

  @ViewChild('nzTreeComponent', {static: false}) nzTreeComponent!: NzTreeComponent;
  defaultCheckedKeys = [];

  nodes: NzTreeNodeOptions[] = [];

  findAgency() {
    this.baseService.get(ApiUrl.AgencyUrl + '/findAgencyByLoginUser',).subscribe(
      data => {
        if (data.status == 0) {
          this.nodes = data.data;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }
}
